package com.love.netty.demo.handler.request;

import com.love.netty.demo.handler.PacketCodecHandler;
import com.love.netty.enums.MsgSignFlagEnum;
import com.love.netty.util.ChannelSuperviseUtils;
import com.love.netty.util.RedisUtils;
import com.love.netty.util.UriUtils;
import io.netty.channel.*;
import io.netty.handler.codec.Headers;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedNioFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.buf.UriUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

/**
 * @ClassName: HttpRequestHandler
 * @Description:
 * @Author: wuj
 * @Date: 2021-07-02 15:00
 **/
@Component
@ChannelHandler.Sharable
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequestHandler.class);


    private static  final  String SOCKET_URL ="/ws";

    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        if (msg.uri().startsWith(SOCKET_URL)) {
            //保存当前发送的人信息
            String userId = UriUtils.getParam(msg.uri(), "userId");
            if (userId != null) {
                // todo: 用户校验，重复登录判断
                //存储消息接收人id
                ChannelSuperviseUtils.addChannel(userId, ctx.channel());
                ctx.fireChannelRead(msg.setUri(SOCKET_URL).retain());
                //判断当前登录的用户是否有离线的消息
                if(redisUtils.exists(userId)){
                    LOGGER.info("接收离线消息");
                    //从redis中获取离线消息的发送人的集合(接收人-发送人)
                    Set<String> set = redisUtils.sSmembers(userId);
                    for (String fromUserId : set) {
                        Channel channel = ChannelSuperviseUtils.getChannelByUserId(fromUserId);
                        //判断当前发送人是否在线
                        if(channel != null){
                            //获取离线消息
                            String key = MsgSignFlagEnum.unsign.getType()+"-"+ fromUserId + "-" +userId;
                            List<String> msgList = redisUtils.lRange(key, 0, -1);
                            //倒序输出语句
                            msgList.stream()
                                    .sorted(Comparator.reverseOrder())
                                    .forEach(s->ctx.channel().writeAndFlush(new TextWebSocketFrame(s).retain()));
                            //读取完离线消息后,需要删除redis中发送人和接收人的关系
                            redisUtils.srem(userId,fromUserId);
                            //删除离线消息
                            redisUtils.delete(key);
                        }
                    }
                }
            } else {
                LOGGER.info("id为空,关闭");
                ctx.close();
            }
        } else {
            ctx.close();
        }
    }

}
